package com.jin.tinker.app;

import androidx.appcompat.app.AppCompatActivity;
import io.reactivex.functions.Consumer;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jin.tinker.R;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.tinker.lib.tinker.TinkerInstaller;

import java.io.File;

/**
 * content:
 * time: 2021/5/12 15:17
 *
 * @author: J
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPermission();
        initViewAndListener();
    }

    private void initViewAndListener() {
        findViewById(R.id.btn_tinker).setOnClickListener(v -> {
            //            tv_show.text = "I'm Hot-Fix"
            ((TextView) findViewById(R.id.tv_show)).setText("小二郎热修复！");
        });
    }

    /**
     * 申请读取权限
     * 判断有没有 更新的包
     * 如果有的话，直接更新
     * （需要冷启动之后才会成功，我测试的时候 有时候需要一两分钟之后 才会成功）
     */
    @SuppressLint("CheckResult")
    private void initPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        //patch_signed_7zip.apk
                        String path = "/sdcard/Tinker/";
                        File dir = new File(path);
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        File file = new File(path, "patch_signed_7zip.apk");
                        if (file.exists()) {
                            if (file.length() > 0) {
                                TinkerInstaller.onReceiveUpgradePatch(MainActivity.this, file.getAbsolutePath());
                            }
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "热修复技术需要用到此权限", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}